package simulaco.web.jsf;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

import org.primefaces.component.picklist.PickList;
import org.primefaces.model.DualListModel;

import simulaco.dto.Materia;

@FacesConverter("materiaConverter")
public class MateriaConverter implements Converter {

    public MateriaConverter() {
    }

    public String getAsString(FacesContext context, UIComponent component, Object value) {

        int codigo = (value instanceof Materia) ? ((Materia) value).getCodigo() : 0;
        return (codigo > 0) ? String.valueOf(codigo) : null;
    }

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {

        Materia materia = null;
        if (component instanceof PickList) {
            @SuppressWarnings("unchecked")
            DualListModel<Materia> dualList = (DualListModel<Materia>) ((PickList) component).getValue();
            for (Object object : dualList.getSource()) {
                String codigo = "" + ((Materia) object).getCodigo();
                if (codigo.equals(value)) {
                    materia = (Materia) object;
                    break;
                }
            }
            if (materia == null)
                for (Object object : dualList.getTarget()) {
                    String codigo = "" + ((Materia) object).getCodigo();
                    if (codigo.equals(value)) {
                        materia = (Materia) object;
                        break;
                    }
                }
        }
        return materia;
    }
}
